from django.shortcuts import render
from coder.models import Coder
from coder.serializer import CoderSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, generics, permissions
from django.shortcuts import render
from django.contrib.auth.models import User
# from snippets.permissions import IsOwnerOrReadOnly
import hashlib
# Create your views here.


def setpassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result


class Login(APIView):
    """
    List all snippets, or create a new snippet.
    """
    def post(self, request, format=None):
        name = request.data.get('name')
        password = request.data.get('password')
        if name and password:
            coder = Coder.objects.filter(name=name).first()
            if coder:
                if password == coder.password:
                    return Response(status=status.HTTP_200_OK)  # 登录成功
                return Response(status=status.HTTP_403_FORBIDDEN)  # 密码错误
            return Response(status=status.HTTP_204_NO_CONTENT)  # 用户不存在
        return Response(status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)  # 没有信息


class Register(APIView):
    """
    Retrieve, update or delete a snippet instance.
    """
    def post(self, request, format=None):
        username = request.data.get('name')
        password = request.data.get('password')
        # 判断注册信息是否齐全
        if username and password:
            serializer = CoderSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(status=status.HTTP_200_OK)  # 注册成功
        return Response(status=status.HTTP_203_NON_AUTHORITATIVE_INFORMATION)  # 没有信息

